﻿using System;
using System.Management.Automation;
using Nivot.PowerShell.WindowsMobile.Rapi2;

namespace Nivot.PowerShell.WindowsMobile.Commands
{
    public abstract class WMCommandBase : PSCmdlet
    {
        private readonly RemoteDeviceManager _deviceManager;
        private readonly CEProxyController _ceProxy;

        [Parameter]
        public SwitchParameter Force { get; set; }

        protected WMCommandBase()
        {
            WriteVerbose("Initializing RemoteDeviceManager"); // not implemented
            _deviceManager = new RemoteDeviceManager();
            _ceProxy = new CEProxyController(Device);
        }

        protected RemoteDevice Device
        {
            get { return _deviceManager.Devices.FirstConnectedDevice; }
        }

        protected CEProxyController CEProxy
        {
            get { return _ceProxy; }
        }

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
            EnsureDeviceConnected();
        }

        protected void EnsureDeviceConnected()
        {
            if (Device == null)
            {
                var ex = new InvalidOperationException("Device not connected.");
                ThrowTerminatingError(new ErrorRecord(ex, "NotConnected", ErrorCategory.OpenError, null));
            }
        }
        
        // HACK: something wrong with CTP2
        public new void WriteVerbose(string text)
        {            
        }
    }
}